package com.zetyun.tiger.connector.jdbc.source.action;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.zetyun.rt.meta.jsonschema.annotation.JsonSchemaFormat;
import com.zetyun.rt.meta.jsonschema.annotation.JsonSchemaTitle;
import com.zetyun.rt.sdk.model.RtEvent;
import com.zetyun.tiger.connector.jdbc.source.JdbcSourceConfig;
import com.zetyun.tiger.connector.jdbc.source.database.parsers.Parsers;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.time.Duration;

@Getter
@Setter
@ToString
public class JdbcSourceParameter {

    @JsonSchemaTitle("用户名")
    @JsonProperty(defaultValue = "jdbc:mysql://172.20.2.6:9030/tiger")
    private String connectionUrl;

    @JsonSchemaTitle("用户名")
    @JsonProperty(defaultValue = "root")
    private String userName;

    @JsonSchemaTitle("密码")
    private String passWord = "";


    @JsonSchemaTitle("查询sql")
    @JsonSchemaFormat(JsonSchemaFormat.SQL)
    @JsonProperty(required = true)
    private String querySql;

    @JsonSchemaTitle("初始化执行延迟")
    @JsonProperty(required = true, defaultValue = "10 s")
    @JsonPropertyDescription("首次执行延迟 格式： 1 s, 2 m, 3 h")
    private String initialDiscoveryOffset;

    @JsonSchemaTitle("执行周期")
    @JsonProperty(required = true, defaultValue = "24 h")
    @JsonPropertyDescription("执行周期 格式： 1 s, 2 m, 3 h")
    private String discoveryInterval;

    @JsonSchemaTitle("队列拉取超时时间")
    @JsonProperty(required = true, defaultValue = "3 s")
    @JsonPropertyDescription("队列拉取超时时间 格式： 1 s, 2 m, 3 h")
    private String pollInterval = getDiscoveryInterval();


    @JsonSchemaTitle("队列大小")
    @JsonProperty(required = true, defaultValue = "300000")
    @JsonPropertyDescription("缓存队列容量默认为 30,000")
    private Integer queueCapacity;

    public JdbcSourceConfig<RtEvent> buildJdbcSourceConfig() {
        return JdbcSourceConfig.<RtEvent>builder()
                .withUrl(getConnectionUrl())
                .withUser(getUserName())
                .withPassword(getPassWord())
                .withQuery(getQuerySql())
                .withInitialDiscoveryOffset(strToDuration(initialDiscoveryOffset))
                .withDiscoveryInterval(strToDuration(discoveryInterval))
                .withPollInterval(strToDuration(pollInterval))
                .withParser(Parsers.rtEvent())
                .withQueueCapacity(queueCapacity)
                .build();
    }


    private Duration strToDuration(String str) {
        String[] arr = str.trim().split(" ");
        long time = Long.parseLong(arr[0]);
        String unit = arr[1];
        if ("s".equals(unit)) {
            return Duration.ofSeconds(time);
        } else if ("m".equals(unit)) {
            return Duration.ofMinutes(time);
        } else {
            return Duration.ofHours(time);
        }
    }
}
